package com.chagee.store.operation.server.service.biz;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chagee.base.utils.*;
import com.chagee.lark.anno.ExceptionLarkNotice;
import com.chagee.lark.enums.UrgentTypeEnum;
import com.chagee.payment.sdk.dto.request.ConfirmOfflineRequest;
import com.chagee.payment.sdk.dto.request.OfflineConfirmPaymentRequest;
import com.chagee.payment.sdk.utils.AjaxResult;
import com.chagee.personnel.api.event.bo.PersonnelInfo;
import com.chagee.personnel.api.event.response.UserOfRolePageRequestResp;
import com.chagee.scm.api.supplier.request.*;
import com.chagee.scm.api.supplier.response.*;
import com.chagee.store.operation.api.bo.*;
import com.chagee.store.operation.api.enums.*;
import com.chagee.store.operation.api.enums.StoreTaskEnum;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.api.request.*;
import com.chagee.store.operation.api.response.*;
import com.chagee.store.operation.api.response.PayResultResponse;
import com.chagee.store.operation.api.response.vo.ConfirmPaymentVO;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.enums.LarkMessageTypeEnum;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.common.utils.CommonUtil;
import com.chagee.store.operation.common.utils.ResponseUtil;
import com.chagee.store.operation.server.component.ReportExportCellWriteHandler;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.*;
import com.chagee.store.operation.server.event.service.StoreConfigurationBaseService;
import com.chagee.store.operation.server.event.service.StoreSettlementBaseService;
import com.chagee.store.operation.server.event.service.TaskExecutionBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderReceiverBaseService;
import com.chagee.store.operation.server.model.bo.*;
import com.chagee.store.operation.server.model.bo.InvoiceDetailBO;
import com.chagee.store.operation.server.model.info.LarkMessageInfo;
import com.chagee.store.operation.server.model.lock.PushFinanceLock;
import com.chagee.store.operation.server.model.vo.FileVO;
import com.chagee.store.operation.server.model.vo.StoreSettlementExcelVO;
import com.chagee.store.operation.server.model.vo.WorkOrderExcelVO;
import com.chagee.store.operation.server.redis.service.RedisLockService;
import com.chagee.store.operation.server.service.YunLiInvoiceService;
import com.chagee.store.operation.server.service.third.*;
import com.chagee.store.operation.server.transfer.SettlementTransfer;
import com.chagee.store.operation.server.transfer.WorkOrderTransfer;
import com.chagee.store.operation.server.utils.DateUtil;
import com.chagee.store.operation.server.utils.HttpRequestUtils;
import com.chagee.storeManagement.api.event.enums.*;
import com.chagee.storeManagement.api.event.param.StoreExt;
import com.chagee.storeManagement.api.event.request.TimerEventRegisterDefaultRequest;
import com.personnel.auth.service.PersonnelAuthService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 打烊结算
 * @Author : hk
 * @Date : 2024/10/14
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class StoreSettlementBizService {

	private static final int EXPORT_PAGE_SIZE = 500;
	private static final int ORDER_EXPORT_PAGE_SIZE = 100;

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Resource
	private StoreDetailMapper storeDetailMapper;
	@Resource
	private StoreMapper storeMapper;

	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;

	@Resource
	private WorkOrderTransfer workOrderTransfer;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private StoreConfigurationMapper storeConfigurationMapper;

	@Resource
	private StoreSettlementBaseService storeSettlementBaseService;

	@Resource
	private WorkOrderBizService workOrderBizService;

	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;

	@Resource
	private StoreConfigurationBaseService storeConfigurationBaseService;

	@Resource
	private ScmThirdService scmThirdService;

	@Resource
	private YunLiInvoiceService yunLiInvoiceService;

	@Resource
	private FinanceBizService financeBizService;

	@Resource
	private RedisLockService redisLockService;

	//网关识别信息 票易通提供
	@Value("${yunLi.authentication}")
	private String authentication;

	//序列号
	@Value("${yunLi.action}")
	private String action;

	//功能代码 票易通提供
	@Value("${yunLi.tenantCode}")
	private String tenantCode;

	// 统一认证 票易通提供
	@Value("${yunLi.uiaSign}")
	private String uiaSign;

	@Value("${yunLi.userCode}")
	private String userCode;

	@Value("${yunLi.userName}")
	private String userName;

	@Value("${yunLi.uploadInvoiceUrl}")
	private String uploadInvoiceUrl;

	@Value("${yunLi.privateKey}")
	private String privateKey;

	@Value("${yunLi.tissue.url}")
	private String tissueUrl;
	@Value("${yunLi.tissue.authentication}")
	private String tissueAuthentication;
	@Value("${yunLi.tissue.action}")
	private String tissueAction;
	@Value("${yunLi.tissue.tenantCode}")
	private String tissueTenantCode;
	@Value("${yunLi.tissue.uiaSign}")
	private String tissueUiaSign;

	@Resource
	private PersonalBizService personalBizService;
	@Resource
	private PersonnelAuthService personnelAuthService;

	@Value("${settlement.issuedRoleAlias:三方打烊项目组负责人}")
	private String issuedRoleAlias;

	@Resource
	private FeiShuSendService feiShuSendService;

	@Value("${settlement.storeVerifyTimeout:259200}")
	private Integer storeVerifyTimeout;

	@Resource
	private EventThirdService eventThirdService;

	@Resource
	private SupplierDetailBizService supplierDetailBizService;

	@Resource
	private PaymentService paymentService;
	@Resource
	private PaymentBizService paymentBizService;


	@Value("${payment.appId}")
	private String appId;
	@Value("${payment.publicKey}")
	private String payPublicKey;
	@Value("${payment.privateKey}")
	private String payPrivateKey;

	@Value("${payment.url}")
	private String url;


	private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

	public PaginationData<SupplierPageQueryResponse> querySupplier(PaginationRequest<QuerySupplierRequest> request) {
		PaginationRequest<SupplierSimpleRequestBO> paginationRequest = new PaginationRequest<>();
		paginationRequest.setPageNum(request.getPageNum());
		paginationRequest.setPageSize(request.getPageSize());

		SupplierSimpleRequestBO searchSupplierBO = new SupplierSimpleRequestBO();
		searchSupplierBO.setChannelType(request.getQueryParameter().getChannelType());
		searchSupplierBO.setOrgCodeList(request.getQueryParameter().getOrgCodeList());
		searchSupplierBO.setSupplierName(request.getQueryParameter().getSupplierName());
		paginationRequest.setQueryParameter(searchSupplierBO);
		PaginationData<SupplierSimpleResponseBO> paginationData = scmThirdService.searchPageByName(paginationRequest);

		PaginationData<SupplierPageQueryResponse> data = new PaginationData<>();
		if (Objects.nonNull(paginationData)) {
			data.setPageNum(paginationData.getPageNum());
			data.setPageSize(paginationData.getPageSize());
			if (Objects.nonNull(paginationData.getPageList()) && CollectionUtils.isNotEmpty(paginationData.getPageList())) {
				List<SupplierPageQueryResponse> responseList = paginationData.getPageList().stream().map(s -> {
					SupplierPageQueryResponse response = new SupplierPageQueryResponse();
					BeanUtil.copyProperties(s, response);
					return response;
				}).collect(Collectors.toList());
				data.setPageList(responseList);
			}
		}
		return data;
	}

	/**
	 * 结算单列表/查询
	 */
	public PaginationData<SettlementResponse> querySettlementPage(PaginationRequest<SettlementRequest> request) {
		Page<StoreSettlementDO> page = new Page<>(request.getPageNum(), request.getPageSize());

		Page<StoreSettlementDO> settlementPage = storeSettlementBaseService.querySettlementPage(page, request.getQueryParameter());

		if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
			return ResponseUtil.emptyResponse(request, SettlementResponse.class, settlementPage.getTotal());
		}
		List<SettlementResponse> list = converToTasktVO(settlementPage.getRecords());
		return ResponseUtil.commonResponse(request, list, settlementPage.getTotal());
	}

	private List<SettlementResponse> converToTasktVO(List<StoreSettlementDO> dos) {

		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
		List<SettlementResponse> list = dos.stream().map(s -> {
			SettlementResponse settlementResponse = new SettlementResponse();
			BeanUtil.copyProperties(s, settlementResponse);
			settlementResponse.setSettlementCycle(sd.format(s.getSettlementCycle()));

			if (StringUtils.isNotBlank(s.getExtra())) {
				SettlementExtJsonBO extJsonBO = JSON.parseObject(s.getExtra(), new TypeReference<SettlementExtJsonBO>() {
				});
				settlementResponse.setExtJsonBO(extJsonBO);
			}
			if (StringUtils.isNotBlank(s.getInvoice())) {
				InvoiceBO invoiceBO  = JSON.parseObject(s.getInvoice(), new TypeReference<InvoiceBO>() {});
				settlementResponse.setInvoiceUrlList(invoiceBO.getInvoiceUrl());
			}
			OrderPenalizeBO orderPenalizeBO  = JSON.parseObject(s.getPenalizeMoney(), new TypeReference<OrderPenalizeBO>() {});
			settlementResponse.setSettlementMoney(orderPenalizeBO.getPayMoney());
			settlementResponse.setFloorPrice(orderPenalizeBO.getFloorPrice());

			return settlementResponse;
		}).collect(Collectors.toList());
		return list;
	}

	/**
	 * 结算单列表/查询
	 */
	public SettlementResponse settlementDetail(SettlementDetailRequest request) {
		if (request == null) {
			throw new BizException(BizErrorCode.PARAMETER_IS_NULL);
		}
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
		LambdaQueryWrapper<StoreSettlementDO> wrapper = new LambdaQueryWrapper();
		if (StringUtils.isNotEmpty(request.getSettlementNo())) {
			wrapper.eq(StoreSettlementDO::getSettlementNo, request.getSettlementNo());
		}
		if (StringUtils.isNotEmpty(request.getStoreNo())) {
			wrapper.eq(StoreSettlementDO::getStoreNo, request.getStoreNo());
		}
		List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.list(wrapper);
		StoreSettlementDO storeSettlementDO = storeSettlementDOS.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.ORDER_NOT_EXIST));
		SettlementResponse response = new SettlementResponse();
		BeanUtil.copyProperties(storeSettlementDO, response);
		response.setSettlementCycle(sd.format(storeSettlementDO.getSettlementCycle()));
		LambdaQueryWrapper<StoreConfigurationDO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StoreConfigurationDO::getStoreCode, request.getStoreNo());
		List<StoreConfigurationDO> storeConfigurationDOS = storeConfigurationMapper.selectList(queryWrapper);
		if (CollectionUtils.isNotEmpty(storeConfigurationDOS)) {
			response.setSupplierEntryDate(storeConfigurationDOS.get(0).getSupplierEntryDate());
		}

		if (StringUtils.isNotBlank(storeSettlementDO.getExtra())) {
			SettlementExtJsonBO extJsonBO = JSON.parseObject(storeSettlementDO.getExtra(), new TypeReference<SettlementExtJsonBO>() {
			});
			response.setExtJsonBO(extJsonBO);
		}
		InvoiceBO orderPenalizeBO = new InvoiceBO();
		if (StringUtils.isNotBlank(storeSettlementDO.getInvoice())) {
			orderPenalizeBO  = JSON.parseObject(storeSettlementDO.getInvoice(), new TypeReference<InvoiceBO>() {});
		}
		response.setInvoiceUrlList(orderPenalizeBO.getInvoiceUrl());

		return response;
	}

	public void export(SettlementRequest requestParam, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		List<SettlementResponse> responses = this.querySettlement(requestParam);

		//excel表头
		List<StoreSettlementExcelVO> settlementExcelVOS = new ArrayList<>();
		String time = DATE_TIME_FORMAT.format(LocalDateTime.now());
		if (CollUtil.isNotEmpty(responses)) {
			//数据库 数据
			settlementExcelVOS = SettlementTransfer.INSTANCE.transferSettlementVOList(responses);
		}
		ExportParams params = new ExportParams(CommonConstant.THIRD_WORK_ORDER, CommonConstant.THIRD_WORK_ORDER, ExcelType.XSSF);
		//导出时排除一些字段
		params.setExclusions(new String[]{});

		// 设置响应头
		response.setCharacterEncoding("UTF-8");
		try {
			String fileName = URLEncoder.encode(CommonConstant.SETTLEMENT_WORK_ORDER +"_"+ time, "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename=" + fileName +".xlsx");
			map.put(NormalExcelConstants.DATA_LIST, settlementExcelVOS);
			map.put(NormalExcelConstants.CLASS, StoreSettlementExcelVO.class);
			map.put(NormalExcelConstants.PARAMS, params);
			map.put(NormalExcelConstants.FILE_NAME, fileName);
		} catch (UnsupportedEncodingException e) {
			log.error("exportSettlement() called with exception => 【requestParam = {}】, 【request = {}】, 【response = {}】, 【map = {}】", requestParam, request, response, map, e);
			throw new BizException(BizErrorCode.DOWNLOAD_EXCEL_FAIL);
		}
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

		PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
	}

	//导出查询
	public List<SettlementResponse> querySettlement(SettlementRequest request) {
		List<StoreSettlementDO> storeSettlementDOS = new ArrayList<>();
		int pageNum = 1;
		Page<StoreSettlementDO> page = new Page<>();
		page.setSize(EXPORT_PAGE_SIZE);
		int currentSize = EXPORT_PAGE_SIZE;

		while (currentSize >= EXPORT_PAGE_SIZE) {
			page.setCurrent(pageNum++);
			Page<StoreSettlementDO> settlementPage = storeSettlementBaseService.querySettlementPage(page, request);
			List<StoreSettlementDO> pageRecords = settlementPage.getRecords();
			currentSize = pageRecords.size();
			if (Objects.equals(currentSize, NumberUtils.INTEGER_ZERO)) {
				break;
			}
			storeSettlementDOS.addAll(pageRecords);
		}

		if (CollectionUtils.isEmpty(storeSettlementDOS)) {
			return new ArrayList<>();
		}
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
		List<SettlementResponse> responses = new ArrayList<>();
		for (StoreSettlementDO storeSettlementDO : storeSettlementDOS) {
			SettlementResponse settlementResponse = new SettlementResponse();
			BeanUtils.copyProperties(storeSettlementDO, settlementResponse);
			settlementResponse.setSettlementType(SettlementTypeEnum.of(storeSettlementDO.getSettlementType()).getDesc());
			if (StringUtils.isNotBlank(storeSettlementDO.getStoreType())) {
				Optional.ofNullable(StoreTypeEnum.queryByType(storeSettlementDO.getStoreType()))
					.ifPresent(s -> settlementResponse.setStoreType(s.getDesc()));
			}
			//settlementResponse.setStoreType(StoreTypeEnum.queryByType(storeSettlementDO.getStoreType()).getDesc());
			settlementResponse.setDocumentStatus(SettlementStatusEnum.of(storeSettlementDO.getDocumentStatus()).getDesc());
			settlementResponse.setSettlementCycle(sd.format(storeSettlementDO.getSettlementCycle()));

			responses.add(settlementResponse);
		}
		return responses;
	}

	public HttpResponse<Boolean> updateStoreArea(UpdateStoreAreaRequest request){
		LambdaQueryWrapper<StoreDO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(StoreDO::getStoreNo, request.getStoreNo());
		wrapper.eq(StoreDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		List<StoreDO> storeDOS = storeMapper.selectList(wrapper);
		StoreDO storeDO = storeDOS.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.STORE_NO_FILE_ERROR));
		if (!storeDO.getClosingTaskStatus().equals(NumberUtils.INTEGER_ONE)) {
			return HttpResponseUtil.build(false, BizErrorCode.NO_CLOSING_TASK_ORDER.getErrorCode(), BizErrorCode.NO_CLOSING_TASK_ORDER.getErrorMsg());
		}

		LambdaQueryWrapper<StoreConfigurationDO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StoreConfigurationDO::getStoreCode, request.getStoreNo());
		List<StoreConfigurationDO> storeConfigurationDOS = storeConfigurationMapper.selectList(queryWrapper);
		StoreConfigurationDO storeConfigurationDO = storeConfigurationDOS.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.ORDER_NOT_EXIST));

		if (ObjectUtils.isNotEmpty(storeConfigurationDO)) {
			storeConfigurationDO.setStoreArea(request.getStoreArea());
			storeConfigurationMapper.updateById(storeConfigurationDO);
		}
		storeSettlementBaseService.updateStoreSettlement(request);

		return HttpResponseUtil.success(true);
	}

	public HttpResponse<Boolean> updateLineNum(UpdateStoreAreaRequest request){
		LambdaQueryWrapper<StoreDO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(StoreDO::getStoreNo, request.getStoreNo());
		wrapper.eq(StoreDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		List<StoreDO> storeDOS = storeMapper.selectList(wrapper);
		StoreDO storeDO = storeDOS.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.STORE_NO_FILE_ERROR));
		if (!storeDO.getClosingTaskStatus().equals(NumberUtils.INTEGER_ONE)) {
			return HttpResponseUtil.build(false, BizErrorCode.NO_CLOSING_TASK_ORDER.getErrorCode(), BizErrorCode.NO_CLOSING_TASK_ORDER.getErrorMsg());
		}
		LambdaQueryWrapper<StoreConfigurationDO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StoreConfigurationDO::getStoreCode, request.getStoreNo());
		List<StoreConfigurationDO> storeConfigurationDOS = storeConfigurationMapper.selectList(queryWrapper);
		StoreConfigurationDO storeConfigurationDO = storeConfigurationDOS.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.ORDER_NOT_EXIST));

		if (ObjectUtils.isNotEmpty(storeConfigurationDO)) {
			storeConfigurationDO.setStoreLineNum(request.getStoreLineNum());
			storeConfigurationMapper.updateById(storeConfigurationDO);
		}
		storeSettlementBaseService.updateStoreSettlement(request);

		return HttpResponseUtil.success(true);
	}

	public PaginationData<WorkOrderResponse> queryOrderList(PaginationRequest<SettlementOrderRequest> request){
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SettlementOrderRequest settlementOrderRequest = request.getQueryParameter();

		if (StringUtils.isEmpty(settlementOrderRequest.getStoreCode()) || ObjectUtils.isEmpty(settlementOrderRequest.getCycle()) || ObjectUtils.isEmpty(settlementOrderRequest.getSupplierNo())) {
			throw new BizException(BizErrorCode.REQUEST_VALID_FAILED);
		}
		PaginationRequest<WorkOrderRequest> workOrderRequest = new PaginationRequest<>();
		workOrderRequest.setPageSize(request.getPageSize());
		workOrderRequest.setPageNum(request.getPageNum());
		WorkOrderRequest queryParameter = new WorkOrderRequest();
		queryParameter.setStoreCode(settlementOrderRequest.getStoreCode());
		Date startOfMonth = null;
		Date endOfMonth = null;
		try {
			startOfMonth = getStartOfMonth(sd.parse(settlementOrderRequest.getCycle()));
			endOfMonth = getEndOfMonth(sd.parse(settlementOrderRequest.getCycle()));
		} catch (ParseException e) {
			throw new BizException(BizErrorCode.DATE_CONVERT_FAIL);
		}
		queryParameter.setCreateTimeStart(sdf.format(startOfMonth));
		queryParameter.setCreateTimeEnd(sdf.format(endOfMonth));
		queryParameter.setSupplierNo(settlementOrderRequest.getSupplierNo());
		workOrderRequest.setQueryParameter(queryParameter);

		return query(workOrderRequest);
	}

	public PaginationData<WorkOrderResponse> query(PaginationRequest<WorkOrderRequest> request){

		List<SearchSupplierResponse> supplierList = supplierDetailBizService.supplierList();
		Map<String, String> supplierMap = supplierList.stream().filter(s -> StringUtils.isNotBlank(s.getCode())).collect(Collectors.toMap(SearchSupplierResponse::getCode, SearchSupplierResponse::getName, (a, b) -> b));

		Page<WorkOrderDO> page = new Page<>(request.getPageNum(), request.getPageSize());

		WorkOrderRequest workOrderRequest = request.getQueryParameter();
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
		wrapper.notIn(WorkOrderDO::getDocumentStatus, Arrays.asList(StoreWorkOrderStatusEnum.EXPIRED.getType()));
		if(workOrderRequest!=null){
			if(workOrderRequest.getWorkOrderNumber()!=null){
				wrapper.like(WorkOrderDO::getWorkOrderNumber,workOrderRequest.getWorkOrderNumber());
			}
			if(workOrderRequest.getStoreCode()!=null){
				wrapper.eq(WorkOrderDO::getStoreCode,workOrderRequest.getStoreCode());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getStoreName())){
				wrapper.like(WorkOrderDO::getStoreName,workOrderRequest.getStoreName());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getSupplierNo())){
				wrapper.eq(WorkOrderDO::getSupplierNo,workOrderRequest.getSupplierNo());
			}
			if(workOrderRequest.getReceiver()!=null){
				wrapper.like(WorkOrderDO::getReceiver,workOrderRequest.getReceiver()).or().like(WorkOrderDO::getReceiverMobile,workOrderRequest.getReceiver());
			}

			if(workOrderRequest.getSupplier()!=null){
				wrapper.like(WorkOrderDO::getSupplier,workOrderRequest.getSupplier());
			}
			if(workOrderRequest.getStoreCategory()!=null){
				wrapper.eq(WorkOrderDO::getStoreCategory,workOrderRequest.getStoreCategory());
			}
			if(workOrderRequest.getCreateTimeStart()!=null){
				wrapper.ge(WorkOrderDO::getCreateTime,workOrderRequest.getCreateTimeStart());
			}
			if(workOrderRequest.getCreateTimeEnd()!=null){
				wrapper.le(WorkOrderDO::getCreateTime,workOrderRequest.getCreateTimeEnd());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getCompanyName()) ) {
				wrapper.eq(WorkOrderDO::getCompanyName, workOrderRequest.getCompanyName());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getIsQualified())) {
				if (OrderAcceptanceEnum.YES.name().equals(workOrderRequest.getIsQualified())) {
					wrapper.ge(WorkOrderDO::getDocumentScore, 80);
				} else if (OrderAcceptanceEnum.NO.name().equals(workOrderRequest.getIsQualified())) {
					wrapper.lt(WorkOrderDO::getDocumentScore, 80);
				}
			}
			if (StringUtils.isNotBlank(workOrderRequest.getAcceptanceType())) {
				wrapper.eq(WorkOrderDO::getAcceptanceType, workOrderRequest.getAcceptanceType());
			}
			wrapper.orderByDesc(WorkOrderDO::getId).orderByDesc(WorkOrderDO::getStoreCode);
		}
		Page<WorkOrderDO> workOrderDOS = workOrderMapper.selectPage(page,wrapper);

		if (CollectionUtils.isEmpty(workOrderDOS.getRecords())) {
			return ResponseUtil.emptyResponse(request, WorkOrderResponse.class, workOrderDOS.getTotal());
		}
		List<WorkOrderDO> workOrderDOList=workOrderDOS.getRecords();
		List<String> storeNoList = workOrderDOList.stream().map(WorkOrderDO::getStoreCode).collect(Collectors.toList());

		List<StoreConfigurationDO> storeConfigurationDOS = storeConfigurationBaseService.batchGetByStoreCodeList(storeNoList);
		Map<String, StoreConfigurationDO> storeConfigurationDOMap = storeConfigurationDOS.stream().collect(Collectors.toMap(StoreConfigurationDO::getStoreCode, Function.identity(), (a, b) -> a));

		List<String> orderNos = workOrderDOList.stream().map(WorkOrderDO::getWorkOrderNumber).collect(Collectors.toList());
		List<TaskExecutionDO> taskExecutionDOS = taskExecutionBaseService.queryTaskList(orderNos);
		Map<String, List<TaskExecutionDO>> taskExecutionMap = taskExecutionDOS.stream().collect(Collectors.groupingBy(TaskExecutionDO::getWorkOrderNumber));

		List<StoreDetailBO> storeDetailBOS = storeDetailMapper.selectListByStoreNos(storeNoList);
		Map<String, StoreDetailBO> map = storeDetailBOS.stream().collect(Collectors.toMap(StoreDetailBO::getStoreNo, Function.identity(), (a, b) -> b));

		LambdaQueryWrapper<WorkOrderReceiverDO> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.in(WorkOrderReceiverDO::getWorkOrderNumber, storeNoList);
		List<WorkOrderReceiverDO> orderReceiverDOS = workOrderReceiverBaseService.list(queryWrapper);
		Map<String, List<WorkOrderReceiverDO>> listMap = orderReceiverDOS.stream().collect(Collectors.groupingBy(WorkOrderReceiverDO::getWorkOrderNumber));

		List<WorkOrderResponse> workOrderResponseList = new LinkedList<>();
		for (WorkOrderDO workOrderDO : workOrderDOS.getRecords()) {
			WorkOrderResponse workOrderResponse = new WorkOrderResponse();
			BeanUtils.copyProperties(workOrderDO,workOrderResponse);
			if(workOrderDO.getReceiver()!=null&&workOrderDO.getReceiverMobile()!=null){
				String[] receiver = workOrderDO.getReceiver().split(",");

				String[] receiverMobile = workOrderDO.getReceiverMobile().split(",");
				List<String> encryptPhoneList = new ArrayList<>();
				for (String phone : receiverMobile) {
					String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
					encryptPhoneList.add(phoneNumber);
				}
				receiverMobile = encryptPhoneList.toArray(new String[0]);
				String result = joinStringArrays(receiver, receiverMobile);
				workOrderResponse.setReceiverAndReceiverMobile(result);
			}
			//添加3.0产品售卖情况
			if (MapUtil.isNotEmpty(map) && null != map.get(workOrderDO.getStoreCode())){
				Product3SalesEnum product3SalesEnum = Product3SalesEnum.of(map.get(workOrderDO.getStoreCode()).getProductThridSalesStatus());
				if (Objects.nonNull(product3SalesEnum)) {
					workOrderResponse.setProductThridSalesStatus(product3SalesEnum.getInfo());
				}
			}
			if (StringUtils.isNotBlank(workOrderDO.getDocumentScore())) {
				workOrderResponse.setIsQualified(Integer.parseInt(workOrderDO.getDocumentScore()) < 80 ? OrderAcceptanceEnum.NO.name() : OrderAcceptanceEnum.YES.name());
			}
			//单个工单对应一个供应商
			if (MapUtil.isNotEmpty(listMap) && CollectionUtils.isNotEmpty(listMap.get(workOrderDO.getWorkOrderNumber()))) {
				WorkOrderReceiverDO workOrderReceiverDO = listMap.get(workOrderDO.getWorkOrderNumber()).stream().findFirst().orElse(null);
				if (Objects.nonNull(workOrderReceiverDO)) {
					workOrderResponse.setSupplierId(workOrderReceiverDO.getSupplierId());
				}
			}

			if (MapUtil.isNotEmpty(storeConfigurationDOMap) && Objects.nonNull(storeConfigurationDOMap.get(workOrderDO.getStoreCode()))) {
				StoreConfigurationDO storeConfigurationDO = storeConfigurationDOMap.get(workOrderDO.getStoreCode());
				workOrderResponse.setFloorPrice(getOrderFloorPrice(workOrderDO, storeConfigurationDO.getFloorPrice()));
				workOrderResponse.setBillingStartDate(storeConfigurationDO.getBillingStartDate());
			}
			List<TaskExecutionDO> executionDOS = taskExecutionMap.get(workOrderDO.getWorkOrderNumber());
			String workOrderRemark = this.getWorkOrderRemark(executionDOS);
			workOrderResponse.setRemark(workOrderRemark);

			if (MapUtil.isNotEmpty(supplierMap) && StringUtils.isNotBlank(supplierMap.get(workOrderDO.getSupplierNo()))) {
				workOrderResponse.setSupplier(supplierMap.get(workOrderDO.getSupplierNo()));
			}
			workOrderResponseList.add(workOrderResponse);
		}
		return ResponseUtil.commonResponse(request, workOrderResponseList, workOrderDOS.getTotal());
	}

	private String getOrderFloorPrice(WorkOrderDO workOrderDO, BigDecimal floorPrice) {
		String orderFloorPrice = CommonConstant.NONE_STRING;

		// 产品:大于四月份默认显示当前的结算底价 (4/16)
		if (DateUtil.dateCompareTo(workOrderDO.getCreateTime())) {
			orderFloorPrice = Objects.nonNull(floorPrice) ? floorPrice.toPlainString() : CommonConstant.NONE_STRING;
		}
		if (StringUtils.isNotBlank(workOrderDO.getExtra())) {
			OrderExtJsonBO extJsonBO = JSON.parseObject(workOrderDO.getExtra(), new TypeReference<OrderExtJsonBO>() {
			});
			if (Objects.nonNull(extJsonBO.getFloorPrice())) {
				orderFloorPrice = extJsonBO.getFloorPrice().toPlainString();
			}
		}
		return orderFloorPrice;
	}

	private String getWorkOrderRemark(List<TaskExecutionDO> executionDOS ) {
		String remark = StringUtils.EMPTY;
		if (CollectionUtils.isNotEmpty(executionDOS)) {
			List<TaskExecutionDO> noTasK = executionDOS.stream().filter(s -> StringUtils.isNotBlank(s.getEarlyAcceptance()) && StoreTaskEnum.NO.getType().equals(s.getEarlyAcceptance())).collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(noTasK)) {
				StringBuilder builderRemark = new StringBuilder();
				for (TaskExecutionDO taskExecutionDO : noTasK) {
					builderRemark.append(taskExecutionDO.getTaskName()).append(":").append(StringUtils.isNotBlank(taskExecutionDO.getRemark()) ? taskExecutionDO.getRemark() : "").append("\n");
				}
				remark = builderRemark.toString();
			}
		}
		return remark;
	}

	@SneakyThrows
	public void orderExport(SettlementOrderRequest orderRequest, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		//List<WorkOrderResponse> workOrderResponseList = queryExport(orderRequest);

		List<SearchSupplierResponse> supplierList = supplierDetailBizService.supplierList();
		Map<String, String> supplierMap = supplierList.stream().filter(s -> StringUtils.isNotBlank(s.getCode())).collect(Collectors.toMap(SearchSupplierResponse::getCode, SearchSupplierResponse::getName, (a, b) -> b));

		CommonUtil.download(response, CommonConstant.THIRD_WORK_ORDER);
		try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), WorkOrderExcelVO.class).build()) {
			WriteSheet writeSheet = EasyExcel.writerSheet(CommonConstant.THIRD_WORK_ORDER).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
				.registerWriteHandler(new ReportExportCellWriteHandler(CommonConstant.THIRD_WORK_ORDER)).build();

			Page<WorkOrderDO> page = new Page<>();
			page.setSize(ORDER_EXPORT_PAGE_SIZE);
			int pageNum = 1;
			int currentSize = ORDER_EXPORT_PAGE_SIZE;
			Page<WorkOrderDO> workOrderDOPage;
			List<WorkOrderResponse> workOrderResponses;
			List<WorkOrderExcelVO> workOrderExcelVoList;
			while (currentSize >= ORDER_EXPORT_PAGE_SIZE) {
				page.setCurrent(pageNum++);
				workOrderDOPage = queryOrderPage(page, orderRequest);
				currentSize = workOrderDOPage.getRecords().size();
				if (CollectionUtils.isEmpty(workOrderDOPage.getRecords())) {
					excelWriter.write(new ArrayList<WorkOrderExcelVO>(), writeSheet);
					break;
				}
				workOrderResponses = queryExport(workOrderDOPage.getRecords(), supplierMap);
				workOrderExcelVoList = workOrderTransfer.workOrderResponse2WorkOrderExcelVOList(workOrderResponses);
				excelWriter.write(workOrderExcelVoList, writeSheet);
			}
		}

		//excel表头
//		List<WorkOrderExcelVO> workOrderExcelVoList = new ArrayList<>();
//		String time = DATE_TIME_FORMAT.format(LocalDateTime.now());
//		if (CollUtil.isNotEmpty(workOrderResponseList)) {
//			workOrderExcelVoList = workOrderTransfer.workOrderResponse2WorkOrderExcelVOList(workOrderResponseList);
//		}
//		ExportParams params = new ExportParams(CommonConstant.THIRD_WORK_ORDER, CommonConstant.THIRD_WORK_ORDER, ExcelType.XSSF);
//		//导出时排除一些字段
//		params.setExclusions(new String[]{});
//
//		// 设置响应头
//		response.setCharacterEncoding("UTF-8");
//		try {
//			String fileName = URLEncoder.encode(CommonConstant.THIRD_WORK_ORDER + "_" + time, "UTF-8").replaceAll("\\+", "%20");
//			response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//			map.put(NormalExcelConstants.DATA_LIST, workOrderExcelVoList);
//			map.put(NormalExcelConstants.CLASS, WorkOrderExcelVO.class);
//			map.put(NormalExcelConstants.PARAMS, params);
//			map.put(NormalExcelConstants.FILE_NAME, fileName);
//		} catch (UnsupportedEncodingException e) {
//			log.error("exportStoreOrder() called with exception => 【requestParam = {}】, 【request = {}】, 【response = {}】, 【map = {}】", orderRequest, request, response, map, e);
//			throw new BizException(BizErrorCode.DOWNLOAD_EXCEL_FAIL);
//		}
//		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//
//		PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
	}

	public Page<WorkOrderDO> queryOrderPage(Page<WorkOrderDO> page, SettlementOrderRequest workOrderRequest) {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startOfMonth = null;
		Date endOfMonth = null;
		if (StringUtils.isNotBlank(workOrderRequest.getCycle())) {
			try {
				startOfMonth = getStartOfMonth(sd.parse(workOrderRequest.getCycle()));
				endOfMonth = getEndOfMonth(sd.parse(workOrderRequest.getCycle()));
			} catch (ParseException e) {
				throw new BizException(BizErrorCode.DATE_CONVERT_FAIL);
			}
		}
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
		wrapper.notIn(WorkOrderDO::getDocumentStatus, Arrays.asList(StoreWorkOrderStatusEnum.EXPIRED.getType()));
		if (Objects.nonNull(workOrderRequest)) {
			if (workOrderRequest.getStoreCode() != null) {
				wrapper.eq(WorkOrderDO::getStoreCode, workOrderRequest.getStoreCode());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getSupplierNo())) {
				wrapper.eq(WorkOrderDO::getSupplierNo, workOrderRequest.getSupplierNo());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getCycle())) {
				wrapper.ge(WorkOrderDO::getCreateTime, sdf.format(startOfMonth));
				wrapper.le(WorkOrderDO::getCreateTime, sdf.format(endOfMonth));
			}
			wrapper.orderByDesc(WorkOrderDO::getId).orderByDesc(WorkOrderDO::getStoreCode);
		}
		Page<WorkOrderDO> workOrderDOS = workOrderMapper.selectPage(page,wrapper);
		return workOrderDOS;
	}

	public List<WorkOrderResponse> queryExport(List<WorkOrderDO> workOrderDOS, Map<String, String> supplierMap) {
		if (CollectionUtils.isEmpty(workOrderDOS)) {
			return new ArrayList<>();
		}
		List<String> storeNoList = workOrderDOS.stream().map(WorkOrderDO::getStoreCode).collect(Collectors.toList());
		List<StoreDetailBO> storeDetailBOS = storeDetailMapper.selectListByStoreNos(storeNoList);
		Map<String, StoreDetailBO> map = storeDetailBOS.stream().collect(Collectors.toMap(StoreDetailBO::getStoreNo, Function.identity(), (a, b) -> b));

		LambdaQueryWrapper<StoreConfigurationDO> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.in(StoreConfigurationDO::getStoreCode, storeNoList);
		List<StoreConfigurationDO> list = storeConfigurationBaseService.list(queryWrapper);
		Map<String, StoreConfigurationDO> configurationDOMap = list.stream().collect(Collectors.toMap(StoreConfigurationDO::getStoreCode, Function.identity(), (a, b) -> a));

		LambdaQueryWrapper<TaskExecutionDO> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.in(TaskExecutionDO::getWorkOrderNumber, workOrderDOS.stream().map(WorkOrderDO::getWorkOrderNumber).collect(Collectors.toList()));
		List<TaskExecutionDO> taskExecutionDOS = taskExecutionBaseService.list(lambdaQueryWrapper);
		Map<String, List<TaskExecutionDO>> stringListMap = taskExecutionDOS.stream().collect(Collectors.groupingBy(TaskExecutionDO::getWorkOrderNumber));

		List<WorkOrderResponse> workOrderResponseList = new LinkedList<>();
		for (WorkOrderDO workOrderDO : workOrderDOS) {
			WorkOrderResponse workOrderResponse = new WorkOrderResponse();
			BeanUtils.copyProperties(workOrderDO, workOrderResponse);
			if (StringUtils.isNotBlank(workOrderDO.getReceiver()) && StringUtils.isNotBlank(workOrderDO.getReceiverMobile())) {
				String[] receiver = workOrderDO.getReceiver().split(",");
				String[] receiverMobile = workOrderDO.getReceiverMobile().split(",");

				List<String> encryptPhoneList = new ArrayList<>();
				for (String phone : receiverMobile) {
					String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
					encryptPhoneList.add(phoneNumber);
				}
				receiverMobile = encryptPhoneList.toArray(new String[0]);
				String result = joinStringArrays(receiver, receiverMobile);
				workOrderResponse.setReceiverAndReceiverMobile(result);
			}
			//添加3.0产品售卖情况
			if (MapUtil.isNotEmpty(map) && null != map.get(workOrderDO.getStoreCode())){
				Product3SalesEnum product3SalesEnum = Product3SalesEnum.of(map.get(workOrderDO.getStoreCode()).getProductThridSalesStatus());
				if (Objects.nonNull(product3SalesEnum)) {
					workOrderResponse.setProductThridSalesStatus(product3SalesEnum.getInfo());
				}
			}
			if (StringUtils.isNotBlank(workOrderDO.getDocumentScore())) {
				workOrderResponse.setIsQualified(Integer.parseInt(workOrderDO.getDocumentScore()) < 80 ? "否" : "是");
			}
			List<TaskExecutionDO> executionDOS = stringListMap.get(workOrderDO.getWorkOrderNumber());
			if (CollectionUtils.isNotEmpty(executionDOS)) {
				List<TaskExecutionDO> noTasK = executionDOS.stream().filter(s -> StringUtils.isNotBlank(s.getEarlyAcceptance()) && StoreTaskEnum.NO.getType().equals(s.getEarlyAcceptance())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(noTasK)) {
					StringBuilder builderRemark = new StringBuilder();
					StringBuilder builderPicture = new StringBuilder();
					for (TaskExecutionDO taskExecutionDO : noTasK) {
						builderRemark.append(taskExecutionDO.getTaskName()).append(":").append(StringUtils.isNotBlank(taskExecutionDO.getRemark()) ? taskExecutionDO.getRemark() : "").append("\n");
						List<FileVO> voList = JSON.parseArray(taskExecutionDO.getRemarkPicture(), FileVO.class);
						List<String> filePathList = new ArrayList<>();
						if (CollectionUtils.isNotEmpty(voList)) {
							filePathList = voList.stream().filter(s -> s != null && StringUtils.isNotBlank(s.getFilePath())).map(FileVO::getFilePath).collect(Collectors.toList());
						}
						builderPicture.append(taskExecutionDO.getTaskName()).append(":").append(filePathList).append("\n");
					}
					workOrderResponse.setRemark(builderRemark.toString());
					workOrderResponse.setRemarkPicture(builderPicture.toString());
				}
			}
			//计费开始时间
			StoreConfigurationDO configurationDO = configurationDOMap.get(workOrderDO.getStoreCode());
			if (Objects.nonNull(configurationDO) && ObjectUtil.isNotEmpty(configurationDO.getBillingStartDate())) {

				workOrderResponse.setBillingStartDate(configurationDO.getBillingStartDate());
			}
			if (Objects.nonNull(configurationDO)) {
				//保留两位小数
				//String floorPrice = configurationDO.getFloorPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString();
				workOrderResponse.setFloorPrice(getOrderFloorPrice(workOrderDO, configurationDO.getFloorPrice()));
			}
			if (Objects.nonNull(configurationDO) && ObjectUtil.isNotEmpty(configurationDO.getNightFloorPrice())) {
				String nightFloorPrice = configurationDO.getNightFloorPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString();
				workOrderResponse.setNightFloorPrice(nightFloorPrice);
			}
			if (StringUtils.isNotBlank(workOrderDO.getAcceptanceType())) {
				workOrderResponse.setAcceptanceType(OrderAcceptanceTypeEnum.queryByType(workOrderDO.getAcceptanceType()).getDesc());
			}
			if (StringUtils.isNotBlank(workOrderDO.getAppealFlag())) {
				workOrderResponse.setAppealFlag(OrderAppealTypeEnum.getByType(workOrderDO.getAppealFlag()).getDesc());
			}

			if (MapUtil.isNotEmpty(supplierMap) && StringUtils.isNotBlank(supplierMap.get(workOrderDO.getSupplierNo()))) {
				workOrderResponse.setSupplier(supplierMap.get(workOrderDO.getSupplierNo()));
			}
			workOrderResponseList.add(workOrderResponse);
		}
		return workOrderResponseList;
	}

	public Boolean supplierVerify(SupplierVerifyRequest request){
		LambdaQueryWrapper<StoreSettlementDO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StoreSettlementDO::getSettlementNo, request.getSettlementNo());
		List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.list(queryWrapper);
		StoreSettlementDO storeSettlementDO = storeSettlementDOS.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.ORDER_NOT_EXIST));

		if (!SettlementStatusEnum.WAIT_SUPPLIER_VERIFY.getType().equals(storeSettlementDO.getDocumentStatus())) {
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}

		SettlementStatusEnum status = SettlementStatusEnum.SUBMIT_INVOICE;
		//storeSettlementDO.setDocumentStatus(SettlementStatusEnum.SUBMIT_INVOICE.getType());

		//加盟店  (若选择不需要上传发票或者 没有选择<超时>)
		if (StringUtils.equals(StoreCategoryEnum.JM.getType(), storeSettlementDO.getStoreCategory()) &&
			(StringUtils.equals(NeedInvoiceEnum.NOT_NEED.getType(), storeSettlementDO.getPushInvoiceFlag()) || Objects.isNull(storeSettlementDO.getPushInvoiceFlag()))) {
			status = SettlementStatusEnum.WAIT_PAY;
			storeSettlementDO.setWaitPayTime(LocalDateTime.now());
		}

		if (storeSettlementDO.getPayMoney().compareTo(BigDecimal.ZERO) <= 0) {
			status = SettlementStatusEnum.COMPLETE;
		}
		storeSettlementDO.setDocumentStatus(status.getType());
		//创建上传发票任务
		createUploadInvoice(storeSettlementDO);
		log.info("{}单据编号创建上传发票任务成功", storeSettlementDO.getSettlementNo());

		return storeSettlementBaseService.updateById(storeSettlementDO);
	}

	public void createUploadInvoice(StoreSettlementDO storeSettlementDO) {
		String storeNo = storeSettlementDO.getStoreNo();
		StoreDetailInfoBO storeDetailInfoBO = storeDetailMapper.selectByStoreNo(storeNo);
		if (StringUtils.isBlank(storeDetailInfoBO.getBusinessLicenseCredit())) {
			throw new BizException(BizErrorCode.PURCHASER_LOCK_TAXNO_ERROR);
		}
		String businessLicenseCompanyName = StringUtils.EMPTY;
		if (StringUtils.isNotBlank(storeDetailInfoBO.getExtData())) {
			StoreExt storeExt = JSON.parseObject(storeDetailInfoBO.getExtData(), new TypeReference<StoreExt>() {
			});
			businessLicenseCompanyName = storeExt.getBusinessLicenseCompanyName();
		}

		PaginationRequest<SearchSupplierBaseBO> paginationRequest = new PaginationRequest<>();
		paginationRequest.setPageNum(CommonConstant.DELETE_FLAG);
		paginationRequest.setPageSize(CommonConstant.PAGE_SIZE_MAX);
		SearchSupplierBaseBO baseBO = new SearchSupplierBaseBO();
		baseBO.setCode(storeSettlementDO.getSupplierNo());
		paginationRequest.setQueryParameter(baseBO);
		PaginationData<SupplierBaseBO> supplierPageData = scmThirdService.searchSupplier(paginationRequest);
		if (Objects.isNull(supplierPageData)) {
			throw new BizException(BizErrorCode.INVOKE_SUPPLIER_ERROR);
		}
		SupplierBaseBO supplierBaseBO = supplierPageData.getPageList().stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.SUPPLIER_ENTRY_ERROR));
		if (StringUtils.isBlank(supplierBaseBO.getUniteCode())) {
			throw new BizException(BizErrorCode.SUPPLIER_LOCK_TAXNO_ERROR);
		}

		//创建上传发票任务
		Map<String, String> headerMap = new HashMap<>();
		headerMap.put("Authentication", authentication);
		headerMap.put("serialNo", storeSettlementDO.getSettlementNo());
		headerMap.put("action", action);
		headerMap.put("tenantCode", tenantCode);
		headerMap.put("uiaSign", uiaSign);

		UploadInvoiceRequest invoiceRequest = new UploadInvoiceRequest();
		invoiceRequest.setBillCode(storeSettlementDO.getSettlementNo());
		invoiceRequest.setBillCodeType(CommonConstant.BILL_CODE_TYPE);
		invoiceRequest.setUserCode(userCode);
		invoiceRequest.setUserName(userName);
		invoiceRequest.setAmountWithTax(String.valueOf(storeSettlementDO.getPayMoney()));
		invoiceRequest.setSource(CommonConstant.SOURCE);
		Map<String, Object> extMap = new HashMap<>();
		extMap.put("ext1", storeSettlementDO.getStoreNo());
		invoiceRequest.setExtFields(extMap);
		invoiceRequest.setBuyerTaxNo(storeDetailInfoBO.getBusinessLicenseCredit()); //统一社会信用代码
		invoiceRequest.setBuyerName(businessLicenseCompanyName); // 购方税号
		invoiceRequest.setSellerName(supplierBaseBO.getName());
		invoiceRequest.setSellerTaxNo(supplierBaseBO.getUniteCode());

		try {
			String uploadResponse = HttpRequestUtils.doPost(uploadInvoiceUrl,headerMap, JSON.toJSONString(invoiceRequest));

			UploadInvoiceResponse uploadInvoiceResponse = JSONObject.parseObject(uploadResponse, new TypeReference<UploadInvoiceResponse>() {});
			log.info("{}单据编号创建上传发票接口返回 {}", storeSettlementDO.getSettlementNo(), JSON.toJSONString(uploadInvoiceResponse));
			if (Objects.isNull(uploadInvoiceResponse) || !uploadInvoiceResponse.getCode().equals(CommonConstant.ONE)) {
				throw new BizException(BizErrorCode.UPLOAD_INVOICE_ERROR);
			}
		} catch (Exception e) {
			log.error("{}单据编号创建上传发票接口异常",storeSettlementDO.getSettlementNo(), e);
			throw new BizException(BizErrorCode.UPLOAD_INVOICE_ERROR);
		}
	}

	public Boolean settlementAdjust(AdjustMoneyRequest request) {
		StoreSettlementDO storeSettlementDO = storeSettlementBaseService.querySettlement(request.getSettlementNo());
		if (!SettlementStatusEnum.SETTLEMENT_ADJUST_TYPE.contains(storeSettlementDO.getDocumentStatus())) {
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}

		BladeUser bladeUser;
		try {
			bladeUser = AuthUtil.getUser();
			log.info("用户{}调整结算单{} 金额: {}", bladeUser.getNickName(), request.getSettlementNo(), request.getAdjustMoney());
		} catch (Exception e) {
			log.error("获取登录人信息失败", e);
		}

		SettlementExtJsonBO extJsonBO = new SettlementExtJsonBO();
		if (StringUtils.isNotBlank(storeSettlementDO.getExtra())) {
			extJsonBO = JSON.parseObject(storeSettlementDO.getExtra(), new TypeReference<SettlementExtJsonBO>() {
			});
		}
		extJsonBO.setRemark(request.getRemark());
		extJsonBO.setRemarkPic(request.getRemarkPic());
		storeSettlementDO.setAdjustMoney(request.getAdjustMoney());
		storeSettlementDO.setExtra(JSONObject.toJSON(extJsonBO).toString());

		OrderPenalizeBO orderPenalizeBO  = JSON.parseObject(storeSettlementDO.getPenalizeMoney(), new TypeReference<OrderPenalizeBO>() {});

		BigDecimal penalizePayMoney = orderPenalizeBO.getPayMoney().setScale(0, RoundingMode.HALF_UP);
		BigDecimal decimal = penalizePayMoney.add(request.getAdjustMoney());
		storeSettlementDO.setPayMoney(decimal);

		//调整金额变更, 状态变更为初始状态(V1.2.9)
		//storeSettlementDO.setDocumentStatus(SettlementStatusEnum.WAIT_STORE_VERIFY.getType());
		storeSettlementBaseService.updateSettlement(storeSettlementDO);

		return true;
	}

	//获取上传发票链接
	public String getUploadInvoiceUrl(InvoiceRequest request) {
		StoreSettlementDO storeSettlementDO = storeSettlementBaseService.querySettlement(request.getSettlementNo());
		if (Objects.isNull(storeSettlementDO)) {
			throw new BizException(BizErrorCode.ORDER_NOT_EXIST);
		}
		//创建上传发票任务
		createUploadInvoice(storeSettlementDO);
		String pushUrl = yunLiInvoiceService.getPushUrl(request.getSettlementNo());
		return pushUrl;
	}

	//发票回调信息
	public Boolean invoiceCallback(InvoiceCallbackRequest request) {

		String requestPrivateKey = request.getPrivateKey();
		if (!privateKey.equals(requestPrivateKey)) {
			log.info("验签失败：{}", JSON.toJSONString(request));
			throw new BizException(BizErrorCode.VISA_VERIFICATION_ERROR);
		}
		InvoiceMainBO invoiceMain = request.getInvoiceMain();

		String billCode = invoiceMain.getBillCode();
		PushFinanceLock lock = null;
		if (StringUtils.isNotBlank(billCode)) {
			lock = new PushFinanceLock(billCode);
		}
		try {
			redisLockService.lockElseThrowError(lock, "请稍后再试");
			StoreSettlementDO storeSettlementDO = storeSettlementBaseService.querySettlement(billCode);
			if (Objects.isNull(storeSettlementDO)) {
				throw new BizException(BizErrorCode.ORDER_NOT_EXIST);
			}
			InvoiceBO invoiceBO = new InvoiceBO();
			if (StringUtils.isNotBlank(storeSettlementDO.getInvoice())) {
				invoiceBO = JSON.parseObject(storeSettlementDO.getInvoice(), new TypeReference<InvoiceBO>() {});
			}
//			List<String> invoiceUrlList = new ArrayList<>();
//			if (CollectionUtils.isNotEmpty(invoiceBO.getInvoiceUrl())) {
//				invoiceUrlList = invoiceBO.getInvoiceUrl();
//			}
//			invoiceUrlList.add(invoiceMain.getImageUrl());
//			invoiceBO.setInvoiceUrl(invoiceUrlList);

			List<InvoiceCallbackRequest> invoiceInfoList = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(invoiceBO.getInvoiceInfo())) {
				invoiceInfoList = invoiceBO.getInvoiceInfo();
			}
			if (CollectionUtil.isNotEmpty(invoiceInfoList)) {
				invoiceInfoList.removeIf(invoiceCallbackRequest -> invoiceCallbackRequest.getInvoiceMain().getInvoiceNo().equals(invoiceMain.getInvoiceNo()));
			}

			invoiceInfoList.add(request);
			List<String> invoiceUrl = invoiceInfoList.stream().map(invoiceCallbackRequest -> invoiceCallbackRequest.getInvoiceMain().getImageUrl()).collect(Collectors.toList());

			invoiceBO.setInvoiceUrl(invoiceUrl);
			invoiceBO.setInvoiceInfo(invoiceInfoList);
			//发票总占用金额大于 支付金额, 则变更状态
			BigDecimal sumInvoiceMoney = invoiceBO.getInvoiceInfo().stream().map(t -> t.getInvoiceMain().getAmountWithTax()).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);
			if (InvoiceCheckStatusEnum.TRUE_SUCCESS.getType().equals(invoiceMain.getCheckStatus()) && SettlementStatusEnum.SUBMIT_INVOICE.getType().equals(storeSettlementDO.getDocumentStatus())
				&& sumInvoiceMoney.compareTo(storeSettlementDO.getPayMoney()) >=0) {
				storeSettlementDO.setDocumentStatus(SettlementStatusEnum.WAIT_PAY.getType());
				//待支付节点时间
				storeSettlementDO.setWaitPayTime(LocalDateTime.now());
			}

			storeSettlementDO.setInvoice(JSON.toJSONString(invoiceBO));
			storeSettlementDO.setPushFinanceStatus(PushFinanceStatusEnum.NOT_PUSH.getType());

			storeSettlementBaseService.updateSettlementInvoice(storeSettlementDO);

			//飞书通知
			LarkMessageInfo messageInfo = new LarkMessageInfo();
			messageInfo.setStoreNo(storeSettlementDO.getStoreNo());
			messageInfo.setType(LarkMessageTypeEnum.submitInvoice.getType());
			messageInfo.setSettlementNo(storeSettlementDO.getSettlementNo());
			feiShuSendService.sendFeiShuMsg(messageInfo);
		} finally {
			redisLockService.unLock(lock);
		}
		return true;
	}

	//推送财务系统
	@ExceptionLarkNotice(bizType = "发票信息推送财务系统", title = "结算单发票信息推送财务系统", urgentType = UrgentTypeEnum.APP_PHONE)
	public void pushFinance(StoreSettlementDO storeSettlementDO) {
		InvoiceBO invoiceBO = JSON.parseObject(storeSettlementDO.getInvoice(), new TypeReference<InvoiceBO>() {});
		List<InvoiceCallbackRequest> invoiceInfo = invoiceBO.getInvoiceInfo();

//		String url = tissueUrl.concat("?orgCode=").concat(storeSettlementDO.getStoreNo());
//		Map<String, String> headers = new HashMap<>();
//		headers.put("Authentication", tissueAuthentication);
//		headers.put("action", tissueAction);
//		headers.put("tenantCode", tissueTenantCode);
//		headers.put("uiaSign", tissueUiaSign);
//		headers.put("serialNo", storeSettlementDO.getStoreNo());

		//获取云砺组织信息
//		String response = HttpRequestUtils.doGet(url, headers);
//		TissueResponse tissueResponse = JSON.parseObject(response, new TypeReference<TissueResponse>() {});
//		OrgResponse orgResponse = tissueResponse.getResult();
//		String parentId = orgResponse.getParentId();
//		List<OrgResponse> parentOrgs = orgResponse.getParentOrgs();
//		Optional<OrgResponse> first = parentOrgs.stream().filter(Objects::nonNull).filter(s -> StringUtils.isNotBlank(s.getOrgId()) && StringUtils.equals(s.getOrgId(), parentId)).findFirst();
//		//云砺系统 1:一般增值税纳税人 2:小规模纳税人
//		String taxpayerQualificationType = "";
//		if (first.isPresent()) {
//			CompanyBO company = first.get().getCompany();
//			taxpayerQualificationType = company.getTaxpayerQualificationType();
//		}
//		Set<String> taxpayerType = Sets.newHashSet(CommonConstant.ONE, CommonConstant.TWO);
//		if (StringUtils.isBlank(taxpayerQualificationType) || !taxpayerType.contains(taxpayerQualificationType)) {
//			throw new BizException(BizErrorCode.YUNLI_RATEPAYER_ERROR);
//		}

		InvoiceDetailBO invoiceDetailBO = new InvoiceDetailBO();
		invoiceDetailBO.setBusinessId(CommonConstant.BUSINESS_ID);
		invoiceDetailBO.setOrgName(storeSettlementDO.getStoreName());
		invoiceDetailBO.setStoreCode(storeSettlementDO.getStoreNo());
//		if (StoreCategoryEnum.ZY.getType().equals(storeSettlementDO.getStoreCategory())) {
//			invoiceDetailBO.setStoreNature(CommonConstant.ZERO);
//		}else if (StoreCategoryEnum.LY.getType().equals(storeSettlementDO.getStoreCategory())) {
//			invoiceDetailBO.setStoreNature(CommonConstant.ONE);
//		}
//		invoiceDetailBO.setStoreType(CommonConstant.ONE.equals(taxpayerQualificationType) ? RatepayerTypeEnum.NORMAL.getType() : RatepayerTypeEnum.SMALL_SCALE.getType());
		invoiceDetailBO.setSupplierName(storeSettlementDO.getSupplier());
		invoiceDetailBO.setSupplierCode(storeSettlementDO.getSupplierNo());
		invoiceDetailBO.setBillNo(storeSettlementDO.getSettlementNo());
		invoiceDetailBO.setPeriod(DateUtil.format(storeSettlementDO.getSettlementCycle(), CommonConstant.DATE_FORMAT));
		invoiceDetailBO.setBillDate(DateUtil.format(storeSettlementDO.getCreateTime(), CommonConstant.DATE_TIME_FORMAT));
		invoiceDetailBO.setCurrency(CommonConstant.CURRENCY);
		invoiceDetailBO.setAmount(storeSettlementDO.getPayMoney().toPlainString());

		//发票信息
		List<InvoiceInfoBO> invoiceInfoBOS = new ArrayList<>();
		for (InvoiceCallbackRequest invoiceCallbackRequest : invoiceInfo) {

			InvoiceMainBO invoiceMain = invoiceCallbackRequest.getInvoiceMain();
			InvoiceInfoBO invoiceInfoBO = new InvoiceInfoBO()
				.setPurchaser(invoiceMain.getPurchaserName())
				.setSeller(invoiceMain.getSellerName())
				.setInvoiceType(InvoiceTypeEnum.queryByInvoiceType(invoiceMain.getInvoiceType()))
				.setInvoiceCode(StringUtils.isNotBlank(invoiceMain.getInvoiceCode()) ? invoiceMain.getInvoiceCode() : "")
				.setInvoiceNo(invoiceMain.getInvoiceNo())
				.setNetAmount(invoiceMain.getAmountWithoutTax())
				.setTaxAmount(invoiceMain.getTaxAmount())
				.setTaxRate(invoiceMain.getTaxRate())
				.setTotalAmount(invoiceMain.getAmountWithTax());
			invoiceInfoBOS.add(invoiceInfoBO);
		}
		invoiceDetailBO.setInvoices(invoiceInfoBOS);
		financeBizService.pushInvoiceDetail(invoiceDetailBO);
	}

	private SupplierBaseBO getSupplier(String supplierNo){
		PaginationRequest<SearchSupplierBaseBO> paginationRequest = new PaginationRequest<>();
		paginationRequest.setPageNum(CommonConstant.DELETE_FLAG);
		paginationRequest.setPageSize(CommonConstant.PAGE_SIZE_MAX);
		SearchSupplierBaseBO baseBO = new SearchSupplierBaseBO();
		baseBO.setCode(supplierNo);
		paginationRequest.setQueryParameter(baseBO);
		PaginationData<SupplierBaseBO> supplierPageData = scmThirdService.searchSupplier(paginationRequest);
		if (Objects.isNull(supplierPageData)) {
			throw new BizException(BizErrorCode.INVOKE_SUPPLIER_ERROR);
		}
		SupplierBaseBO supplierBaseBO = supplierPageData.getPageList().stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.SUPPLIER_ENTRY_ERROR));

		return supplierBaseBO;
	}


	private static String joinStringArrays(String[] name, String[] phone) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < name.length; i++) {
			sb.append(name[i]).append("(").append(phone[i % phone.length]).append("),");
		}
		return sb.deleteCharAt(sb.lastIndexOf(",")).toString();
	}

	public static Date getStartOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

	public static Date getEndOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return calendar.getTime();
	}

	/**
	 * 结算单下发
	 * @param issuedRequest
	 * @return
	 */
	public Boolean issued(SettlementIssuedRequest issuedRequest) {

		PersonnelInfo loginUser = personnelAuthService.getLoginUserInfoInWeb();
		log.info("settlement_issued_loginUser{},request:{}", JSONObject.toJSONString(loginUser), JSONObject.toJSONString(issuedRequest));

		//三方打烊项目组负责人
		List<UserOfRolePageRequestResp> users = personalBizService.getUserOfRolePage(issuedRoleAlias);

		List<Long> userIds = users.stream().map(UserOfRolePageRequestResp::getId).collect(Collectors.toList());
		if (!userIds.contains(loginUser.getId())) {
			throw new BizException(BizErrorCode.LOGIN_USER_UNAUTHORIZED_OPERATION_ERROR);
		}


		List<String> settlementNos = issuedRequest.getSettlementNos();

		List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.batchQuerySettlement(settlementNos);
		boolean anyMatch = storeSettlementDOS.stream().anyMatch(s -> !SettlementStatusEnum.SETTLEMENT_ISSUED_TYPE.contains(s.getDocumentStatus()));
		if (anyMatch) {
			throw new BizException(BizErrorCode.ORDER_STATUS_ERROR);
		}
		storeSettlementDOS.forEach(s -> {
			storeSettlementBaseService.update(SettlementStatusEnum.WAIT_STORE_VERIFY.getType(), StringUtils.EMPTY, s);
		});

		//超过72小时; 则默认门店已确认
		try {
			Long expiredDate = System.currentTimeMillis() + (storeVerifyTimeout * 1000L);
			LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(expiredDate), ZoneId.systemDefault());

			List<TimerEventRegisterDefaultRequest> requestList = new ArrayList<>();
			storeSettlementDOS.forEach(s -> {
				TimerEventRegisterDefaultRequest request = new TimerEventRegisterDefaultRequest();
				request.setEventType(EventTypeEnum.WAIT_STORE_VERIFY_TIME_OUT);
				request.setBizCode(s.getSettlementNo());
				request.setBizData(null);
				request.setTimer(dateTime);
				requestList.add(request);
			});
			eventThirdService.registerDefaultTimerEvent(requestList);
		} catch (Exception e) {
			log.error("结算单下发注册失败", e);
		}
		return true;

	}

	public Boolean supplierRejected(SupplierRejectedRequest request) {
		StoreSettlementDO storeSettlementDO = storeSettlementBaseService.querySettlement(request.getSettlementNo());
		if (Objects.isNull(storeSettlementDO)) {
			throw new BizException(BizErrorCode.ORDER_NOT_EXIST);
		}
		if (!StringUtils.equals(SettlementStatusEnum.WAIT_SUPPLIER_VERIFY.getType(), storeSettlementDO.getDocumentStatus())) {
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}

		SettlementExtJsonBO extJsonBO = new SettlementExtJsonBO();
		if (StringUtils.isNotBlank(storeSettlementDO.getExtra())) {
			extJsonBO = JSON.parseObject(storeSettlementDO.getExtra(), new TypeReference<SettlementExtJsonBO>() {
			});
		}
		extJsonBO.setSupplierRejectedReason(request.getSupplierRejectedReason());
		extJsonBO.setSupplierRejectedAttachment(request.getSupplierRejectedAttachment());

		storeSettlementBaseService.update(SettlementStatusEnum.SUPPLIER_OBJECTION.getType(), JSON.toJSONString(extJsonBO), storeSettlementDO);

		//飞书通知
		feiShuSendService.supplierRejectedMsg(storeSettlementDO);

		return true;
	}

	/**
	 * 线下支付
	 * @param request
	 * @return
	 */
	public Boolean offlinePay(OfflinePayRequest request) {

		log.info("StoreSettlementBizService_offlinePay request:{}", JSON.toJSONString(request));

		String settlementNo = request.getSettlementNo();
		StoreSettlementDO storeSettlementDO = storeSettlementBaseService.querySettlement(settlementNo);
		if (Objects.isNull(storeSettlementDO)) {
			throw new BizException(BizErrorCode.ORDER_NOT_EXIST);
		}
		if (!SettlementStatusEnum.WAIT_PAY.getType().equals(storeSettlementDO.getDocumentStatus())) {
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}
		if (PayTypeEnum.OFFLINE.getType().equals(storeSettlementDO.getPayType())) {
			throw new BizException(BizErrorCode.PAY_OFFLINE_FAILED);
		}

		SettlementExtJsonBO extJsonBO = new SettlementExtJsonBO();
		if (StringUtils.isNotBlank(storeSettlementDO.getExtra())) {
			extJsonBO = JSON.parseObject(storeSettlementDO.getExtra(), new TypeReference<SettlementExtJsonBO>() {
			});
		}
		extJsonBO.setPayDocuments(request.getPayDocuments());

		// 未点击上线支付操作
		if (StringUtils.isBlank(storeSettlementDO.getPaymentNo())) {
			//创建交易单
			String paymentNo = paymentBizService.createOrder(storeSettlementDO, request.getCreatePersonId());
			if (StringUtils.isBlank(paymentNo)) {
				throw new BizException(BizErrorCode.ADVANCE_PAYMENT_CREATE_FAILED);
			}
			storeSettlementDO.setPaymentNo(paymentNo);
			storeSettlementBaseService.updatePayInfo(storeSettlementDO.getSettlementNo(), storeSettlementDO.getPaymentNo(), StringUtils.EMPTY, StringUtils.EMPTY);
		}

		//付款金额 单位分
		BigDecimal amount = storeSettlementDO.getPayMoney().multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP);

		OfflineConfirmPaymentRequest paymentRequest = new OfflineConfirmPaymentRequest();
		paymentRequest.setPrice(amount.intValue());
		paymentRequest.setOrderNos(Collections.singletonList(storeSettlementDO.getPaymentNo()));
		paymentRequest.setPayChannelCode(CommonConstant.PAY_CHANNEL);
		paymentRequest.setPayPersonName(request.getPayPersonName());
		AjaxResult result = paymentService.offlinePay(paymentRequest, payPublicKey, payPrivateKey, url, appId);

		if (Objects.isNull(result)) {
			throw new BizException(BizErrorCode.OFFLINE_PAY_FAILED);
		}

		PayResultResponse<ConfirmPaymentVO> payResultResponse = JSONObject.parseObject(JSON.toJSONString(result), new TypeReference<PayResultResponse<ConfirmPaymentVO>>() {
		});
		if (!payResultResponse.getCode().equals(CommonConstant.ZERO)) {
			throw new BizException(BizErrorCode.OFFLINE_PAY_FAILED, payResultResponse.getMsg());
		}
		ConfirmOfflineRequest offlineRequest = new ConfirmOfflineRequest();
		offlineRequest.setOrderNoLists(Collections.singletonList(storeSettlementDO.getPaymentNo()));
		offlineRequest.setStatus(CommonConstant.PAY_CONFIRM_STATUS);
		AjaxResult payConfirmResult = paymentService.offlinePayConfirm(offlineRequest, payPublicKey, payPrivateKey, url, appId);

		if (Objects.isNull(payConfirmResult)) {
			throw new BizException(BizErrorCode.OFFLINE_PAY_CONFIRM_FAILED);
		}
		PayResultResponse<Boolean> payConfirmResponse = JSONObject.parseObject(JSON.toJSONString(payConfirmResult), new TypeReference<PayResultResponse<Boolean>>() {
		});

		if (!payConfirmResponse.getCode().equals(CommonConstant.ZERO)) {
			throw new BizException(BizErrorCode.OFFLINE_PAY_CONFIRM_FAILED, payConfirmResponse.getMsg());
		}
		storeSettlementBaseService.updatePayInfo(storeSettlementDO.getSettlementNo(), StringUtils.EMPTY, PayTypeEnum.OFFLINE.getType(), JSON.toJSONString(extJsonBO));

		return true;

	}



}


















